package cn.jhz.learn.community_dynamic.wbms.controller.api;

import cn.jhz.learn.community_dynamic.common.bean.JsonData;
import cn.jhz.learn.community_dynamic.common.exception.RequestException;
import cn.jhz.learn.community_dynamic.common.util.RequestHelper;
import cn.jhz.learn.community_dynamic.common.util.VerifyHelper;
import cn.jhz.learn.community_dynamic.dao.RoleJpaRepository;
import cn.jhz.learn.community_dynamic.dao.UserJpaRepository;
import cn.jhz.learn.community_dynamic.manager.UserManager;
import cn.jhz.learn.community_dynamic.model.UserEntity;
import cn.jhz.learn.community_dynamic.vo.wbms.ColumnType;
import cn.jhz.learn.community_dynamic.vo.wbms.UserView;
import cn.jhz.learn.community_dynamic.security.helper.LoginHelper;
import cn.jhz.learn.community_dynamic.security.helper.ViewAdpt;
import cn.jhz.learn.community_dynamic.service.CodeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("api/")
public class AuthUserController {
    private final CodeService smsCodeService;
    private final UserJpaRepository userJpaRepository;
    private final RoleJpaRepository roleJpaRepository;
    private final UserManager userManager;

    @Autowired
    public AuthUserController(CodeService smsCodeService, UserJpaRepository userJpaRepository, RoleJpaRepository roleJpaRepository, UserManager userManager) {
	this.userJpaRepository = userJpaRepository;
        this.smsCodeService = smsCodeService;
        this.userManager = userManager;
        this.roleJpaRepository = roleJpaRepository;
    }
    
    @GetMapping("auth/user/per_info")
    @PreAuthorize("hasAuthority('user::per_info')")
    public JsonData getInfo() {
	return JsonData.newSuccessInstance(ViewAdpt.newWbmsDetailsInstance((UserEntity) LoginHelper.getLoginUser().get()));
    }
    
    @GetMapping("auth/user/list")
    @PreAuthorize("hasAuthority('user::get_list')")
    public JsonData getList(@RequestParam("pn") Integer pageNum,@RequestParam("ps") Integer pageSize) {
	// TODO 根据管理员等级获取列表
	return JsonData.newSuccessInstance(this.userJpaRepository.findAll(PageRequest.of(pageNum-1, pageSize)).map(UserView.adpt));
    }
    
    @PostMapping("auth/user/add")
    @PreAuthorize("hasAuthority('user::add')")
    public JsonData add(@RequestBody UserView user) {
	/*
	 * 使用默认密码、默认头像、默认个性化信息 验证同名、同手机、同邮箱
	 */
	VerifyHelper.verify(user, (columnType) -> {
	    switch (columnType) {
	    case EMAIL:
		// 校验是否存在相同
		if (this.userJpaRepository.existsByemail(user.getEmail())) {

		    throw new RequestException("邮箱已被注册!");
		}
		break;
	    case MOBILE:
		if (this.userJpaRepository.existsByphone(user.getMobile())) {

		    throw new RequestException("手机号已被注册!");
		}
		break;
	    case USERNAME:
		if (this.userJpaRepository.existsByusername(user.getUsername())) {

		    throw new RequestException("用户名已被使用!");
		}
		break;
	    case USERPIC:
		// TODO 其他合法性校验
		break;
	    case ROLES:
		if (user.getRoleIds().size() > 0) {
		    if (this.roleJpaRepository.countByIdIn(user.getRoleIds()) != user.getRoleIds().size()) {

			throw new RequestException("存在无效角色!");
		    }
		}
		break;
	    case STATUS:
	    case PASSWORD:
	    case LOGIN_ID:
		break;
	    default:
		VerifyHelper.defaultAction.accept(columnType);
	    }
	});

	return JsonData.newSuccessInstance(
		UserView.adpt.apply(this.userManager.addInstance(this.userManager.newInstanceByUser(user))));

    }
    
    
    
    @PatchMapping("auth/user/info")
    @PreAuthorize("hasAuthority('user::patch_info')")
    public JsonData patch(@RequestBody UserView user) {

	VerifyHelper.verify(user, (columnType) -> {
	    switch (columnType) {
	    case EMAIL:
		// 校验是否存在相同
		if (this.userJpaRepository.existsByemail(user.getEmail())) {

		    throw new RequestException("邮箱已被使用!");
		}
		break;
	    case MOBILE:
		if (this.userJpaRepository.existsByphone(user.getMobile())) {

		    throw new RequestException("手机号已被使用!");
		}
		break;
	    case USERNAME:
		if (this.userJpaRepository.existsByusername(user.getUsername())) {

		    throw new RequestException("用户名已被使用!");
		}
		break;
	    case LOGIN_ID:
		if (!this.userJpaRepository.existsByloginId(user.getLoginId())) {

		    throw new RequestException("账号不存在!");
		}
		break;
	    case USERPIC:
		// TODO 其他合法性校验
		break;
	    case ROLES:
		if (user.getRoleIds().size() > 0) {
		    if (this.roleJpaRepository.countByIdIn(user.getRoleIds()) != user.getRoleIds().size()) {

			throw new RequestException("存在无效角色!");
		    }
		}
		break;
	    case STATUS:
	    case PASSWORD:
		break;
	    default:
		VerifyHelper.defaultAction.accept(columnType);
	    }
	});
	UserEntity entity = this.userJpaRepository.findByLoginId(user.getLoginId()).get();
	for (ColumnType columnType : RequestHelper.getPatchColumns()) {
	    switch (columnType) {
	    case EMAIL:
		// 校验是否存在相同
		this.userManager.updateInstanceColumn(entity, columnType, user.getEmail());
		break;
	    case MOBILE:
		this.userManager.updateInstanceColumn(entity, columnType, user.getMobile());
		break;
	    case USERNAME:
		this.userManager.updateInstanceColumn(entity, columnType, user.getUsername());
		break;
	    case PASSWORD:
		this.userManager.updateInstanceColumn(entity, columnType, user.getPassword());
		break;
	    case USERPIC:
		this.userManager.updateInstanceColumn(entity, columnType, user.getUserpic());
		break;
	    case ROLES:
		this.userManager.updateInstanceColumn(entity, columnType, user.getRoleIds());
		break;
	    case STATUS:
		this.userManager.updateInstanceColumn(entity, columnType, user.getStatus());
		break;
	    default:
		break;
	    }
	}

	return JsonData.newSuccessInstance(UserView.adpt.apply(entity));
    }
    
}